package com.zl.ots.page;

import com.zl.ots.OtsRedisUtil;
import com.zl.ots.utils.JsonUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Data
@Accessors(chain = true)
@Slf4j
public class OtsPage implements Serializable {

    /**
     * 查询签名
     */
    private String querySign;

    /**
     * 当前token
     */
    private String nowToken;

    private static final String OTS_QUERY_PAGE_SIGN_KEY = "ots-query-page:sign:";

    public static final String FIRST_OTS_TOKEN = "first_token";

    /**
     * 分页的token集合
     */
    private List<String> pageTokens = new ArrayList<>();

    private OtsRedisUtil redisUtil;

    public OtsPage(OtsRedisUtil redisUtil, String  querySign, String nowToken){
        this.querySign = querySign;
        this.nowToken = nowToken;
        this.redisUtil = redisUtil;
        this.pageTokens = getPageTokens(this.querySign);
    }

    /**
     * 获取前一个token
     */
    public String getBeforeToken(){
        if(ObjectUtils.isEmpty(pageTokens)){
            return null;
        }
        for(int i =0 ; i< this.pageTokens.size() ; i++){
            String token = this.pageTokens.get(i);
            if(token.equals(nowToken) && i > 0){
                return this.pageTokens.get(i - 1);
            }
        }
        if(this.pageTokens.size() == 1){
            return FIRST_OTS_TOKEN;
        }
        //如果没有前置token,说明是第一页
        return null;
    }

    /**
     * 添加下一个token
     * @param nextToken nextToken
     */
    public void addNextToken(String nextToken){
        if(!this.pageTokens.contains(nextToken)) {
            this.pageTokens.add(nextToken);
            this.redisUtil.set(OTS_QUERY_PAGE_SIGN_KEY + this.querySign, JsonUtil.toJsonStr(this.pageTokens),30, TimeUnit.MINUTES);
        }
    }

    /**
     * 获取当前token
     */
    public String getNowToken(){
        if(ObjectUtils.isEmpty(this.pageTokens)){
            //如果查询不到缓存，说明搜索条件变了，搜索条件变了分页无效，需从第一页重新开始查
            return null;
        }
        return this.nowToken;
    }

    /**
     * 查询缓存的分页token
     * @param querySign 查询签名
     * @return 分页token集合
     */
    private List<String> getPageTokens(String querySign){
        Object o = redisUtil.get(OTS_QUERY_PAGE_SIGN_KEY + querySign);
        if(ObjectUtils.isEmpty(o)){
            return new ArrayList<>();
        }
        try {
            return JsonUtil.toList(String.valueOf(o), String.class);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return new ArrayList<>();
        }
    }

}
